from django.contrib import admin
from django.forms import widgets
from apps.blog.models import *
from apps.blog.forms import ArticleAdminForm
from django.contrib.admin import SimpleListFilter
from django.utils.html import format_html
from import_export import resources, fields
from import_export.admin import ImportExportModelAdmin
from import_export.admin import ImportExportActionModelAdmin
from import_export.admin import ExportActionMixin
from import_export.widgets import ForeignKeyWidget
from django.contrib.auth import get_user_model

User = get_user_model()


# https://github.com/django-import-export/django-import-export/issues/758
# Register your models here.

class ArticleResource(resources.ModelResource):
    user = fields.Field(
        column_name='user',
        attribute='user',
        widget=ForeignKeyWidget(User, 'username'))

    email = fields.Field(
        column_name='email',
        attribute="email",
        widget=ForeignKeyWidget(User, 'email'))

    last_answerer = fields.Field(
        column_name='last_answerer',
        attribute='last_answerer',
        widget=ForeignKeyWidget(User, 'username'))

    def __init__(self, input_contract=None):
        super(ArticleResource, self).__init__()
        field_list = Article._meta.fields
        self.verbose_name_dict = {}
        for i in field_list:
            self.verbose_name_dict[i.name] = i.verbose_name

    # 默认导入导出field的column_name为字段的名称，这里修改为字段的verbose_name
    def get_export_fields(self):
        fields = self.get_fields()
        for field in fields:
            field_name = self.get_field_name(field)
            # 如果有设置 verbose_name，则将 column_name 替换为 verbose_name, 否则维持原有的字段名。
            if field_name in self.verbose_name_dict.keys():
                field.column_name = self.verbose_name_dict[field_name]
        return fields

    class Meta:
        skip_unchanged = True  # 是否跳过的记录出现在导入结果对象
        report_skipped = False  # 所有记录将被导入
        # export_order = ('id', )
        model = Article


class NodeFilter(SimpleListFilter):
    title = 'node'  # or use _('country') for translated title
    parameter_name = 'node'

    def lookups(self, request, model_admin):
        # 查出 node 的 id 和 name 值 用来显示在网页上的筛选条件
        nodes = Node.objects.all()
        return [(node.id, node.name + "-自定义") for node in nodes]

    def queryset(self, request, queryset):
        if self.value():
            # 筛选条件有值时, 查询对应的 node 的文章，用 title 正排序
            return queryset.filter(node__id=self.value()).order_by("title")
        else:
            # 筛选条件没有值时，全部的时候是没有值的
            return queryset


class SourceAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', 'url']
    list_display_links = ['id', 'name', 'url']


class CategoryAdmin(admin.ModelAdmin):
    list_display = list_display_links = ['id', 'name', 'slug']
    readonly_fields = ('slug',)


class NodeAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', 'slug', 'category', 'num_topics', 'show_status']
    list_display_links = ['id', 'name', 'slug', 'category', 'num_topics']
    list_editable = ["show_status", ]
    readonly_fields = ('slug',)


class TagAdmin(admin.ModelAdmin):
    list_display = ['id', 'name', 'slug']
    list_display_links = ['id', 'name', 'slug']
    readonly_fields = ('slug',)


# class ArticleAdmin(admin.ModelAdmin):
class ArticleAdmin(ImportExportActionModelAdmin):
    # change_list_template = "change_list_custom.html"  # 自定义的模板名称
    form = ArticleAdminForm  # 指定了表单，就不要再用 formfield_overrides 了

    def get_actions(self, request):
        # 列表禁用删除操作
        actions = super(ArticleAdmin, self).get_actions(request)
        if 'delete_selected' in actions and not request.user.is_superuser:
            del actions['delete_selected']
        return actions

    def has_add_permission(self, request, obj=None):
        # 编辑和列表页面非超管禁用 add 按钮
        if request.user.is_superuser:
            return True
        return False

    def show_status_button(self, obj):
        return format_html('<a href="{}" title="查看站点">{}</a>', obj.id, obj.show_status)

    show_status_button.short_description = "审核"

    def get_list_display(self, request):
        """
        Return a sequence containing the fields to be displayed on the
        changelist.
        """
        if request.user.is_superuser:
            list_display = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'show_status', 'slug', 'user',
                            'show_status_button', 'time_create']
            return list_display
        else:
            list_display = ['thumb_shouw', 'title', 'node', 'num_views', 'show_status', 'slug', 'user',
                            'show_status_button', ]
            return list_display

    # list_display = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'show_status', 'slug', 'user',
    #                 'show_status_button', 'time_create']

    list_display_links = ['id', 'thumb_shouw', 'title', 'node', 'num_views', 'user']
    list_filter = ['id', 'source__name', NodeFilter]
    search_fields = ['title_short', 'user', 'content']
    # list_editable = ["show_status", ]
    # style_fields = {"content": "ueditor"}
    readonly_fields = ('slug',)
    show_detail_fields = ['show_status', ]
    resource_class = ArticleResource

    # 重写 字段类型 的 widget, attrs 属性可以设置前端样式
    # formfield_overrides = {
    #     models.IntegerField: {'widget': widgets.NumberInput(attrs={"style": "width:50em;", })},
    #     models.CharField: {'widget': widgets.TextInput(attrs={"style": "width:50%;", "placeholder": "请输入内容"})},
    # }


class FriendsURLAdmin(admin.ModelAdmin):
    change_list_template = "change_list_custom_json.html"  # 自定义的模板名称
    list_display = ['id', 'friend_name', 'site_name', 'show_status', 'site_link', "json_field"]
    list_display_links = ['id', 'friend_name', 'site_name', 'site_link']

    # list_editable = ["show_status", ]

    save_as_continue = False

    def has_add_permission(self, request, obj=None):
        # 编辑页面非超管禁用 add 按钮
        if request.user.is_superuser:
            return False
        return False

    def has_delete_permission(self, request, obj=None):
        # 编辑页面非超管禁用 add 按钮
        if request.user.is_superuser:
            return False
        return False


admin.site.register(Article, ArticleAdmin)
admin.site.register(Source, SourceAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Node, NodeAdmin)
admin.site.register(Tag, TagAdmin)
admin.site.register(FriendsURL, FriendsURLAdmin)
